<template>
  <div class="social">
    <el-row :gutter="20">
      <!-- 发布动态 -->
      <el-col :span="24">
        <el-card>
          <el-form :model="postForm" label-width="80px">
            <el-form-item label="分享内容">
              <el-input
                v-model="postForm.content"
                type="textarea"
                :rows="4"
                placeholder="分享您的旅游经历..."
              />
            </el-form-item>
            <el-form-item label="添加图片">
              <el-upload
                ref="uploadRef"
                :action="uploadAction"
                :headers="uploadHeaders"
                :data="uploadData"
                :name="'images'"
                :file-list="postImageFiles"
                :on-success="handleImageSuccess"
                :on-error="handleImageError"
                :on-remove="handleImageRemove"
                :before-upload="beforeImageUpload"
                :limit="9"
                :multiple="true"
                list-type="picture-card"
                :class="{ 'hide-upload': postImageFiles.length >= 9 }"
                :disabled="posting"
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 JPG、PNG、GIF 格式，单张图片不超过5MB，最多9张
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="createPost" :loading="posting">
                发布动态
              </el-button>
              <el-button @click="resetPostForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 搜索和筛选 -->
      <el-col :span="24" style="margin-top: 20px">
        <el-card>
          <el-form :inline="true" :model="searchForm">
            <el-form-item label="搜索">
              <el-input
                v-model="searchForm.keyword"
                placeholder="搜索动态内容..."
                clearable
                @clear="handleSearch"
                @keyup.enter="handleSearch"
                style="width: 300px"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="handleSearch"
              />
            </el-form-item>
            <el-form-item label="排序">
              <el-select
                v-model="searchForm.ordering"
                placeholder="选择排序方式"
                @change="handleSearch"
                style="width: 150px"
              >
                <el-option label="最新发布" value="-created_at" />
                <el-option label="最早发布" value="created_at" />
                <el-option label="最多点赞" value="-likes_count" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 动态列表 -->
      <el-col :span="24" style="margin-top: 20px">
        <el-card>
          <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px">
              <span>动态广场</span>
              <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap">
                <el-tag v-if="hasActiveFilters" type="info" closable @close="resetSearch">
                  已筛选 {{ posts.length }} 条动态
                </el-tag>
                <el-tag v-if="searchForm.keyword" type="primary" closable @close="clearKeyword" style="margin-left: 5px">
                  关键词: {{ searchForm.keyword }}
                </el-tag>
                <el-tag v-if="searchForm.dateRange && searchForm.dateRange.length === 2" type="success" closable @close="clearDateRange" style="margin-left: 5px">
                  时间: {{ searchForm.dateRange[0] }} 至 {{ searchForm.dateRange[1] }}
                </el-tag>
              </div>
            </div>
          </template>

          <div v-loading="loading">
            <div v-if="posts.length > 0">
              <div
                v-for="post in posts"
                :key="post.id"
                class="post-item"
              >
                <el-card shadow="hover">
                  <div class="post-header">
                    <el-avatar :src="post.user_avatar">
                      {{ post.user_username?.charAt(0).toUpperCase() }}
                    </el-avatar>
                    <div class="post-user-info">
                      <h4
                        style="cursor: pointer; color: #C8102E;"
                        @click="$router.push(`/user/${post.user_id || post.user}`)"
                      >
                        {{ post.user_username }}
                      </h4>
                      <span class="post-time">{{ formatTime(post.created_at) }}</span>
                    </div>
                    <div v-if="isMyPost(post)" class="post-actions-header">
                      <el-button
                        type="primary"
                        size="small"
                        :icon="Edit"
                        @click="editPost(post)"
                      >
                        编辑
                      </el-button>
                      <el-button
                        type="danger"
                        size="small"
                        :icon="Delete"
                        @click="deletePost(post)"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>

                  <div class="post-content">
                    <p>{{ post.content }}</p>
                    <!-- 动态图片展示 -->
                    <div v-if="post.post_images && post.post_images.length > 0" class="post-images">
                      <LazyImage
                        v-for="(img, index) in post.post_images"
                        :key="index"
                        :src="getImageUrl(img.image || img)"
                        :preview-src-list="post.post_images.map(i => getImageUrl(i.image || i))"
                        :initial-index="index"
                        fit="cover"
                        width="100%"
                        height="200px"
                        image-class="post-image-item"
                      />
                    </div>
                  </div>

                  <div class="post-actions">
                    <el-button
                      :type="post.is_liked ? 'danger' : 'default'"
                      :icon="post.is_liked ? 'HeartFilled' : 'Heart'"
                      @click="toggleLike(post)"
                    >
                      {{ post.likes_count || 0 }}
                    </el-button>
                    <el-button
                      type="default"
                      icon="ChatLineRound"
                      @click="showCommentDialog(post)"
                    >
                      {{ post.comments_count || 0 }}
                    </el-button>
                    <el-dropdown trigger="click" @command="(cmd) => shareToPlatform(post, cmd)">
                      <el-button type="default" :icon="Share">
                        分享
                        <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="wechat">
                            <el-icon><ChatLineRound /></el-icon>
                            分享到微信
                          </el-dropdown-item>
                          <el-dropdown-item command="weibo">
                            <el-icon><Share /></el-icon>
                            分享到微博
                          </el-dropdown-item>
                          <el-dropdown-item command="qq">
                            <el-icon><Message /></el-icon>
                            分享到QQ
                          </el-dropdown-item>
                          <el-dropdown-item command="copy">
                            <el-icon><CopyDocument /></el-icon>
                            复制链接
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>

                  <!-- 评论区域 -->
                  <div v-if="post.showComments" class="comments-section">
                    <el-divider />
                    <div v-if="post.comments && post.comments.length > 0">
                      <div
                        v-for="comment in post.comments"
                        :key="comment.id"
                        class="comment-item"
                      >
                        <el-avatar :size="32" :src="comment.user_avatar">
                          {{ comment.user_username?.charAt(0).toUpperCase() }}
                        </el-avatar>
                        <div class="comment-content">
                          <strong>{{ comment.user_username }}</strong>
                          <span>{{ comment.content }}</span>
                          <span class="comment-time">{{ formatTime(comment.created_at) }}</span>
                        </div>
                      </div>
                    </div>
                    <el-input
                      v-model="commentForm.content"
                      placeholder="写评论..."
                      @keyup.enter="addComment(post.id)"
                    >
                      <template #append>
                        <el-button @click="addComment(post.id)">发送</el-button>
                      </template>
                    </el-input>
                  </div>
                </el-card>
              </div>
              
              <!-- 加载更多按钮 -->
              <div v-if="hasMore" style="text-align: center; margin-top: 20px;">
                <el-button @click="loadMore" :loading="loading">
                  加载更多
                </el-button>
              </div>
            </div>
            <el-empty v-else description="暂无动态，快来分享您的旅游经历吧！">
              <el-button type="primary" @click="resetPostForm">发布第一条动态</el-button>
            </el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑动态对话框 -->
    <el-dialog
      v-model="editing"
      title="编辑动态"
      width="600px"
      @close="editingPostId = null; editForm.content = ''"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="内容">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="6"
            placeholder="编辑动态内容..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editing = false; editingPostId = null; editForm.content = ''">
          取消
        </el-button>
        <el-button type="primary" @click="updatePost" :loading="posting">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Plus, Search, Share, ArrowDown, Message, CopyDocument, ChatLineRound } from '@element-plus/icons-vue'
import TravelAPI from '../api/travel'
import LazyImage from '../components/LazyImage.vue'
import axios from 'axios'
import logger from '../utils/logger'
import { getApiBaseUrl } from '../utils/apiConfig'

export default {
  name: 'Social',
  components: {
    LazyImage,
    Search
  },
  setup() {
    const store = useStore()
    const loading = ref(false)
    const posting = ref(false)
    const editing = ref(false)
    const posts = ref([])
    const currentPostId = ref(null)
    const editingPostId = ref(null)
    const postImages = ref([])
    const postImageFiles = ref([])
    const uploadRef = ref(null)
    const pendingImages = ref([]) // 待上传的图片文件

    const currentUser = computed(() => store.state.user)
    
    // 服务端分页显示动态（优化性能）
    const pageSize = ref(10) // 每页显示10条（服务端分页）
    const currentPage = ref(1)
    const totalCount = ref(0)
    const hasMore = computed(() => posts.value.length < totalCount.value)

    const postForm = reactive({
      content: ''
    })

    const editForm = reactive({
      content: ''
    })

    const commentForm = reactive({
      content: ''
    })

    const searchForm = reactive({
      keyword: '',
      dateRange: null,
      ordering: '-created_at',
      user_id: null // 按用户筛选
    })

    // 计算是否有活动的筛选条件
    const hasActiveFilters = computed(() => {
      return !!(searchForm.keyword || (searchForm.dateRange && searchForm.dateRange.length === 2) || searchForm.user_id)
    })

    /**
     * 拉取动态列表（服务端分页）
     */
    const fetchPosts = async () => {
      loading.value = true
      try {
        const params = {}
        
        // 添加搜索参数
        if (searchForm.keyword) {
          params.search = searchForm.keyword
        }
        
        // 添加时间范围参数
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          params.date_from = searchForm.dateRange[0]
          params.date_to = searchForm.dateRange[1]
        }
        
        // 添加排序参数
        if (searchForm.ordering) {
          params.ordering = searchForm.ordering
        }
        
        // 添加用户筛选参数
        if (searchForm.user_id) {
          params.user_id = searchForm.user_id
        }
        
        // 服务端分页参数
        params.page = currentPage.value
        params.page_size = pageSize.value

        const response = await TravelAPI.getPostsWithParams(params)
        const results = response?.results || []
        totalCount.value = response?.count ?? results.length
        posts.value = results.map(post => ({
          ...post,
          showComments: false
        }))
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '获取动态列表失败' })
        })
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      currentPage.value = 1 // 重置到第一页
      fetchPosts()
    }

    const resetSearch = () => {
      searchForm.keyword = ''
      searchForm.dateRange = null
      searchForm.ordering = '-created_at'
      searchForm.user_id = null
      currentPage.value = 1
      fetchPosts()
    }

    // 清除单个筛选条件
    const clearKeyword = () => {
      searchForm.keyword = ''
      handleSearch()
    }

    const clearDateRange = () => {
      searchForm.dateRange = null
      handleSearch()
    }

    // 上传图片相关
    const uploadAction = computed(() => {
      const baseUrl = getApiBaseUrl()
      if (currentPostId.value) {
        return `${baseUrl}/api/social/posts/${currentPostId.value}/upload_images/`
      }
      return ''
    })

    const uploadHeaders = computed(() => {
      const token = store.state.token || localStorage.getItem('token')
      return {
        'Authorization': token ? `Token ${token}` : ''
      }
    })

    const uploadData = computed(() => {
      return {}
    })

    const beforeImageUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        ElMessage.error('只能上传图片文件！')
        return false
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB！')
        return false
      }
      // 如果是发布前选择的图片，先保存到待上传列表，阻止自动上传
      if (!currentPostId.value) {
        pendingImages.value.push(file)
        // 将文件添加到预览列表
        const fileObj = {
          uid: Date.now() + Math.random(),
          name: file.name,
          url: URL.createObjectURL(file),
          status: 'ready',
          raw: file
        }
        postImageFiles.value.push(fileObj)
        return false // 阻止自动上传
      }
      return true // 允许上传（动态已创建）
    }

    const handleImageSuccess = (response) => {
      if (response.images) {
        const newImages = response.images.map(img => ({
          id: img.id,
          url: getImageUrl(img.image),
          name: `image_${img.id}.jpg`
        }))
        postImages.value = [...postImages.value, ...newImages]
        ElMessage.success('图片上传成功')
        fetchPosts()
      }
    }

    const handleImageError = (error) => {
      ElMessage.error('图片上传失败：' + (error.message || '未知错误'))
    }

    const handleImageRemove = (file) => {
      // 从列表中移除
      const index = postImageFiles.value.findIndex(item => item.uid === file.uid)
      if (index > -1) {
        postImageFiles.value.splice(index, 1)
      }
    }

    const createPost = async () => {
      if (!postForm.content.trim()) {
        ElMessage.warning('请输入内容')
        return
      }

      posting.value = true
      try {
        // 先创建动态
        const response = await TravelAPI.createPost({
          content: postForm.content
        })
        
        if (response.id) {
          currentPostId.value = response.id
          
          // 如果有待上传的图片，立即上传
          if (pendingImages.value.length > 0) {
            try {
              const formData = new FormData()
              pendingImages.value.forEach((file) => {
                formData.append('images', file)
              })
              
              const token = store.state.token || localStorage.getItem('token')
              const baseUrl = getApiBaseUrl()
              
              await axios.post(
                `${baseUrl}/api/social/posts/${response.id}/upload_images/`,
                formData,
                {
                  headers: {
                    'Authorization': token ? `Token ${token}` : '',
                    'Content-Type': 'multipart/form-data'
                  }
                }
              )
              
              ElMessage.success('动态和图片发布成功')
              pendingImages.value = []
            } catch (uploadError) {
              ElMessage.warning('动态发布成功，但图片上传失败，您可以稍后重新上传')
              logger.error('图片上传失败:', uploadError)
            }
          } else {
            ElMessage.success('发布成功')
          }
          
          // 重置表单
          resetPostForm()
          fetchPosts()
        }
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '发布动态失败，请重试' })
        })
      } finally {
        posting.value = false
      }
    }
    
    const finishPost = () => {
      // 完成发布，重置表单
      resetPostForm()
      ElMessage.success('发布完成')
    }
    
    const resetPostForm = () => {
      postForm.content = ''
      postImages.value = []
      postImageFiles.value = []
      pendingImages.value = []
      currentPostId.value = null
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
    }
    
    const getImageUrl = (url) => {
      if (!url) return ''
      if (url.startsWith('http')) return url
      if (url.startsWith('/media/')) {
        const baseUrl = getApiBaseUrl()
        return `${baseUrl}${url}`
      }
      return url
    }

    const toggleLike = async (post) => {
      try {
        if (post.is_liked) {
          await TravelAPI.unlikePost(post.id)
          post.is_liked = false
          post.likes_count = (post.likes_count || 1) - 1
        } else {
          await TravelAPI.likePost(post.id)
          post.is_liked = true
          post.likes_count = (post.likes_count || 0) + 1
        }
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '点赞操作失败' })
        })
      }
    }

    /**
     * 分享到其他平台
     */
    const shareToPlatform = (post, platform) => {
      const postUrl = `${window.location.origin}/social/post/${post.id}`
      const title = `南昌旅游 - ${post.user_username}的动态`
      const content = post.content.length > 100 ? post.content.substring(0, 100) + '...' : post.content
      const image = post.post_images && post.post_images.length > 0 ? getImageUrl(post.post_images[0].image || post.post_images[0]) : ''

      switch (platform) {
        case 'wechat': {
          // 微信分享（需要微信JS-SDK，这里提供链接）
          ElMessage.info('请使用微信扫一扫功能分享，或复制链接发送给好友')
          copyToClipboard(postUrl)
          break
        }
        case 'weibo': {
          // 微博分享
          const weiboUrl = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(postUrl)}&title=${encodeURIComponent(title + ' ' + content)}`
          window.open(weiboUrl, '_blank', 'width=600,height=400')
          break
        }
        case 'qq': {
          // QQ分享
          const qqUrl = `https://connect.qq.com/widget/shareqq/index.html?url=${encodeURIComponent(postUrl)}&title=${encodeURIComponent(title)}&summary=${encodeURIComponent(content)}&pics=${encodeURIComponent(image)}`
          window.open(qqUrl, '_blank', 'width=600,height=400')
          break
        }
        case 'copy': {
          // 复制链接
          copyToClipboard(postUrl)
          break
        }
        default:
          ElMessage.warning('未知的分享平台')
      }
    }

    /**
     * 复制到剪贴板
     */
    const copyToClipboard = (text) => {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(() => {
          ElMessage.success('链接已复制到剪贴板')
        }).catch(() => {
          // 降级方案
          fallbackCopyToClipboard(text)
        })
      } else {
        fallbackCopyToClipboard(text)
      }
    }

    /**
     * 降级复制方案
     */
    const fallbackCopyToClipboard = (text) => {
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      try {
        document.execCommand('copy')
        ElMessage.success('链接已复制到剪贴板')
      } catch (err) {
        ElMessage.error('复制失败，请手动复制')
      }
      document.body.removeChild(textArea)
    }

    const showCommentDialog = async (post) => {
      post.showComments = !post.showComments
      if (post.showComments && !post.comments) {
        try {
          // 直接分页获取评论，避免拉取所有帖子
          const resp = await TravelAPI.getPostComments(post.id, { page_size: 50 })
          const comments = resp?.results || resp || []
          post.comments = comments
        } catch (error) {
          import('../utils/logger').then(({ logger }) => {
            logger.error('获取评论失败:', error)
          })
        }
      }
    }

    const isMyPost = (post) => {
      if (!currentUser.value) return false
      return post.user_id === currentUser.value.id || post.user === currentUser.value.id
    }

    const editPost = (post) => {
      editingPostId.value = post.id
      editForm.content = post.content
      editing.value = true
    }

    const updatePost = async () => {
      if (!editForm.content.trim()) {
        ElMessage.warning('请输入内容')
        return
      }

      try {
        await TravelAPI.updatePost(editingPostId.value, {
          content: editForm.content
        })
        ElMessage.success('更新成功')
        editing.value = false
        editingPostId.value = null
        editForm.content = ''
        fetchPosts()
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '更新动态失败' })
        })
        let errorMessage = '更新失败'
        if (error.response) {
          const status = error.response.status
          if (status === 400) {
            errorMessage = error.response.data?.error || error.response.data?.detail || '请求参数错误'
          } else if (status === 401) {
            errorMessage = '登录已过期，请重新登录'
          } else if (status === 403) {
            errorMessage = '没有权限编辑此动态'
          } else if (status === 404) {
            errorMessage = '动态不存在'
          } else if (error.response.data?.error) {
            errorMessage = error.response.data.error
          } else if (error.response.data?.detail) {
            errorMessage = error.response.data.detail
          }
        } else if (error.message) {
          errorMessage = error.message
        }
        ElMessage.error(errorMessage)
      }
    }

    const deletePost = async (post) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除这条动态吗？删除后无法恢复。',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await TravelAPI.deletePost(post.id)
        ElMessage.success('删除成功')
        fetchPosts()
      } catch (error) {
        if (error !== 'cancel') {
          import('../utils/errorHandler').then(({ handleApiError }) => {
            handleApiError(error, { defaultMessage: '删除动态失败' })
          })
          let errorMessage = '删除失败'
          if (error.response) {
            const status = error.response.status
            if (status === 401) {
              errorMessage = '登录已过期，请重新登录'
            } else if (status === 403) {
              errorMessage = '没有权限删除此动态'
            } else if (status === 404) {
              errorMessage = '动态不存在'
            } else if (error.response.data?.error) {
              errorMessage = error.response.data.error
            } else if (error.response.data?.detail) {
              errorMessage = error.response.data.detail
            }
          } else if (error.message) {
            errorMessage = error.message
          }
          ElMessage.error(errorMessage)
        }
      }
    }

    const addComment = async (postId) => {
      if (!commentForm.content.trim()) {
        ElMessage.warning('请输入评论内容')
        return
      }

      try {
        await TravelAPI.addComment(postId, commentForm.content)
        ElMessage.success('评论成功')
        commentForm.content = ''
        fetchPosts()
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '评论失败' })
        })
        let errorMessage = '评论失败'
        if (error.response) {
          const status = error.response.status
          if (status === 400) {
            errorMessage = error.response.data?.error || error.response.data?.detail || '请求参数错误'
          } else if (status === 401) {
            errorMessage = '登录已过期，请重新登录'
          } else if (status === 403) {
            errorMessage = '没有权限评论'
          } else if (error.response.data?.error) {
            errorMessage = error.response.data.error
          } else if (error.response.data?.detail) {
            errorMessage = error.response.data.detail
          }
        } else if (error.message) {
          errorMessage = error.message
        }
        ElMessage.error(errorMessage)
      }
    }

    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      const now = new Date()
      const diff = now - date
      const minutes = Math.floor(diff / 60000)
      const hours = Math.floor(minutes / 60)
      const days = Math.floor(hours / 24)

      if (minutes < 1) return '刚刚'
      if (minutes < 60) return `${minutes}分钟前`
      if (hours < 24) return `${hours}小时前`
      if (days < 7) return `${days}天前`
      return date.toLocaleDateString()
    }

    onMounted(() => {
      fetchPosts()
    })

    /**
     * 加载更多（服务端分页）
     */
    const loadMore = async () => {
      if (!hasMore.value || loading.value) return
      loading.value = true
      try {
        const params = {}
        if (searchForm.keyword) params.search = searchForm.keyword
        if (searchForm.dateRange && searchForm.dateRange.length === 2) {
          params.date_from = searchForm.dateRange[0]
          params.date_to = searchForm.dateRange[1]
        }
        if (searchForm.ordering) params.ordering = searchForm.ordering
        if (searchForm.user_id) params.user_id = searchForm.user_id
        params.page = currentPage.value + 1
        params.page_size = pageSize.value
        const response = await TravelAPI.getPostsWithParams(params)
        const results = response?.results || []
        totalCount.value = response?.count ?? totalCount.value
        posts.value = posts.value.concat(results.map(p => ({ ...p, showComments: false })))
        currentPage.value += 1
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '加载更多失败' })
        })
      } finally {
        loading.value = false
      }
    }

    return {
      loading,
      posting,
      editing,
      posts,
      totalCount,
      hasMore,
      loadMore,
      postForm,
      editForm,
      commentForm,
      currentPostId,
      editingPostId,
      postImages,
      currentUser,
      createPost,
      finishPost,
      resetPostForm,
      getImageUrl,
      uploadAction,
      uploadHeaders,
      uploadData,
      beforeImageUpload,
      handleImageSuccess,
      handleImageError,
      handleImageRemove,
      postImageFiles,
      uploadRef,
      Plus,
      toggleLike,
      showCommentDialog,
      addComment,
      formatTime,
      isMyPost,
      editPost,
      updatePost,
      deletePost,
      Edit,
      Delete,
      searchForm,
      hasActiveFilters,
      handleSearch,
      resetSearch,
      clearKeyword,
      clearDateRange,
      shareToPlatform,
      copyToClipboard,
      Search,
      Share,
      ArrowDown,
      Message,
      CopyDocument,
      ChatLineRound
    }
  }
}
</script>

<style scoped>
.social {
  max-width: 900px;
  margin: 0 auto;
  padding: clamp(10px, 2vw, 20px);
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
  animation: fadeIn 0.5s ease-in;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .social {
    padding: 10px;
  }
  
  .post-item .el-card {
    border-radius: 12px;
  }
  
  .post-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .post-actions {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .post-actions .el-button {
    flex: 1;
    min-width: calc(50% - 5px);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.post-item {
  margin-bottom: 25px;
}

.post-item .el-card {
  border-radius: 16px;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.post-item .el-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 32px rgba(200, 16, 46, 0.2);
  border-color: rgba(212, 175, 55, 0.3);
}

.post-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.post-actions-header {
  display: flex;
  gap: 10px;
}

.post-user-info {
  margin-left: 12px;
  flex: 1;
}

.post-user-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.post-time {
  font-size: 12px;
  color: #909399;
}

.post-content {
  margin: 20px 0;
  color: #606266;
  line-height: 1.8;
  font-size: 15px;
  white-space: pre-wrap;
  word-break: break-word;
}

.post-actions {
  display: flex;
  gap: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.post-actions .el-button {
  border-radius: 20px;
  padding: 8px 20px;
}

.comments-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.comment-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 12px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.comment-content {
  margin-left: 12px;
  flex: 1;
}

.comment-content strong {
  margin-right: 8px;
  color: #303133;
  font-weight: 600;
}

.comment-content span {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.comment-time {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

:deep(.el-card__header) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  padding: 20px;
  border-bottom: 2px solid #f0f0f0;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  min-height: 100px;
}

.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 15px;
}

.post-image-item {
  width: 150px;
  height: 150px;
  border-radius: 8px;
  cursor: pointer;
  object-fit: cover;
}
</style>

